{-#LANGUAGE RecordWildCards,ScopedTypeVariables#-}
module App.Article.Controller(enterArticle,controllerArticle) where
import Miso
import Miso.String
import AppEvent
import App.Article.Event
import App.Article.Model
import AppModel
import Lib.MD
import qualified Data.Text as DT

enterArticle = do
    articleList <- fetchArticle 0
    pure $ ArticleEv $ RespArticle articleList

controllerArticle::Event -> ViewModel -> Effect Action ViewModel
controllerArticle (RespArticle alist) m = noEff $ m {articleModel = ArticleModel {articleList = alist,showArticle = Nothing } }
controllerArticle (OpenDetailArticle openIdx) m@ViewModel{..} = m {viewStack = ("PageDetail" : viewStack),
                                                                   articleModel = ArticleModel {
                                                                       articleList = (articleList articleModel),
                                                                       showArticle = Nothing}} <#  do 
    article <- fetchArticleDetail openIdx
    htmlCtx::MisoString <- renderMD $ toMisoString (dContext article)
    pure $ ArticleEv $ RespDetailArticle $ article {dContext = fromMisoString htmlCtx}
controllerArticle (RespDetailArticle article) m@ViewModel{..} = noEff $ m {articleModel = ArticleModel 
                                                                            {articleList = (articleList articleModel),showArticle = Just article}}
controllerArticle (RefreshDetailArticle openIdx) m@ViewModel{..} = m { articleModel = ArticleModel {
                                                                       articleList = (articleList articleModel),
                                                                       showArticle = Nothing}} <# do 
    article <- fetchArticleDetail openIdx
    htmlCtx::MisoString <- renderMD $ toMisoString (dContext article)
    pure $ ArticleEv $ RespDetailArticle article {dContext = fromMisoString htmlCtx}

